package org.chz.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.util.Pair;
import org.chz.system.CandidateResult;
import org.chz.system.Dictionary;
import org.chz.utils.EditDistanceUtil;
import org.chz.utils.SplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

@Service
public class KeyRecommendService {
    @Autowired
    private Dictionary dictionary;
    @Autowired
    private SplitUtil splitUtil;

    private static final int MAX_HEAP_SIZE = 8;
    private static final int DIST = 5;

    @Async
    public CompletableFuture<Collection<CandidateResult>> doQuery(String word) {
        List charList = splitUtil.splitString(word);
        Set<Integer> unionSet = dictionary.findUnion(charList);

        List<Pair<String, Integer>> dict = dictionary.getDict();/*java泛型会有类型擦除，这里需要把Pair加上*/

        /* 维护一个小顶堆*/
        PriorityQueue<CandidateResult> heap = new PriorityQueue<>();

        unionSet.forEach((lineNum) -> {
            Pair<String, Integer> pair = dict.get(lineNum);

            int distance;
            if (( distance = EditDistanceUtil.editDistance(word, pair.getKey())) < DIST) {
                CandidateResult cdd = new CandidateResult(pair, distance);

                if (heap.size() < MAX_HEAP_SIZE) {
                    heap.add(cdd);
                }else if(heap.peek().compareTo(cdd) > 0) {
                    heap.remove();
                    heap.add(cdd);
                }
            }
        });

        return CompletableFuture.completedFuture(heap);
    }




}
